package org.example.context;

import cn.hutool.core.convert.Convert;
import com.alibaba.ttl.TransmittableThreadLocal;
import org.apache.commons.lang3.StringUtils;
import org.example.domain.system.constant.SecurityConstant;
import org.example.domain.system.model.LoginUser;
import org.example.web.exception.ServerException;
import org.example.web.result.BaseErrorCode;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 获取当前线程变量中的 用户id、用户名称、Token等信息
 */
public class SecurityContextHolder {
    private static final TransmittableThreadLocal<Map<String, Object>> THREAD_LOCAL = new TransmittableThreadLocal<>();


    public static void set(String key, Object value) {
        Map<String, Object> threadLocalMap = getThreadLocalMap();
        threadLocalMap.put(key, value == null ? StringUtils.EMPTY : value);


    }

    public static String get(String key) {
        Map<String, Object> threadLocalMap = getThreadLocalMap();
        String str = Convert.toStr(threadLocalMap.getOrDefault(key, StringUtils.EMPTY));
        if (StringUtils.isEmpty(str)){
            throw new ServerException(BaseErrorCode.IDEMPOTENT_TOKEN_VERIFY_ERROR);
        }
        return str;
    }

    public static Map<String, Object> getThreadLocalMap() {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (map == null) {
            map = new ConcurrentHashMap<String, Object>();
            THREAD_LOCAL.set(map);
        }
        return map;
    }


    public static void setUserId(Long userId) {
        set(SecurityConstant.SECURITY_USER_ID, userId);
    }

    public static Long getUserId() {
        return Long.valueOf(get(SecurityConstant.SECURITY_USER_ID));
    }

    public static void setUserName(String userName) {
        set(SecurityConstant.SECURITY_USER_NAME, userName);
    }

    public static String getUserName() {
        return get(SecurityConstant.SECURITY_USER_NAME);
    }

    public static void setTokenKey(String token) {
        set(SecurityConstant.SECURITY_TOKEN_KEY, token);
    }

    public static String getTokenKey() {
        return get(SecurityConstant.SECURITY_TOKEN_KEY);
    }

    public static void setLoginUser(Object loginUser) {
        set(SecurityConstant.SECURITY_LOGIN_USER, loginUser);
    }

    public static LoginUser getLoginUser() {
        Map<String, Object> threadLocalMap = getThreadLocalMap();
        return (LoginUser) threadLocalMap.getOrDefault(SecurityConstant.SECURITY_LOGIN_USER, new LoginUser());
    }

    public static void remove() {
        THREAD_LOCAL.remove();
    }


}
